import React from "react";
import {ChartMap} from "@/pages/dv/charts/chartsMap";
import dvTool from "@/pages/dv/dvTool";

interface IProps {
  chartOption: DV.IChart
}

interface IState {
  loading: boolean;
  chartOption: DV.IChart
}

/**
 * 组件实例挂载
 * 1、初始化渲染，识别组件类型动态挂载，动态懒加载依赖模块
 * 2、初始化加载数据，每个组件的数据存放到统一的数据池容器中
 * 3、负责更新渲染，当配置改变时负责更新组件
 * 4、负责强制重新渲染
 */
export default class ChartRender extends React.PureComponent<IProps, IState>{

  public uid: string;

  constructor(props: IProps) {
    super(props);
    this.uid = this.props.chartOption.uid || '';
    this.state = {
      chartOption: Object.assign({}, props.chartOption),
      loading: false,
    }
  }

  componentDidMount(): void {

  }

  /**
   * 重新加载数据
   */
  reLoadData = () =>{

  }

  /**
   * 重新挂载
   */
  reload = (interval: number = 0, onload: (chartOption: DV.IChart) => void) =>{

    this.setState({
      loading: true,
    }, () => {
      // 获取最新的配置文件
      setTimeout(() => {
        const newConfig = dvTool.getChartConfig(this.uid);
        this.setState({
          chartOption: newConfig,
          loading: false,
        }, () => {
          if(typeof onload === 'function') onload(newConfig)
        })
      }, interval);
    })
  }


  render(): React.ReactNode {
    return <React.Fragment>
      {
        !this.state.loading && <ChartMap
          chartOption={this.state.chartOption}
          actions={{
            reload: this.reload
          }}
        />
      }
    </React.Fragment>
  }
}
